package controller;


import com.github.pagehelper.PageInfo;
import constant.Constant;
import entity.User;
import exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import service.UserService;
import util.AjaxResult;
import util.CommonUtil;
import util.CommonUtil.MyImage;
import util.ParameterUtil;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @RequestMapping("/getCode.do")
    public void getCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("UserController.getCode()");
        MyImage m = CommonUtil.getImage(null, 4, true, true);
        System.out.println("code=" + m.getCode());
        request.getSession().setAttribute(Constant.SESSION_CODE, m.getCode());
        ServletOutputStream responseOutputStream = response.getOutputStream();
        // 输出图象到页面
        ImageIO.write(m.getImage(), "JPEG", responseOutputStream);
        // 以下关闭输入流！
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    /**
     * 用户数据管理,查询用户信息
     *
     * @param request
     * @return
     */
    @RequestMapping("/findBackUser.do")
    @ResponseBody
    public AjaxResult findBackUser(HttpServletRequest request) {
        PageInfo<User> pageInfo = userService.queryAllUsers(request);
        AjaxResult result = AjaxResult.isOk("查询成功", pageInfo);
        return result;
    }

    /**
     * 用户数据管理,修改用户信息时候，先查询
     * success : function(data){
     * $("#myModal").modal("show");
     * $("#user_id").val(data.obj.id);
     * $("#username").val(data.obj.nickname);
     * $("#roleName").val(data.obj.role);
     * $("#email").val(data.obj.email);
     * }不需要分页
     *
     * @param request
     * @return
     */
    @RequestMapping("/showBackUser.do")
    @ResponseBody
    public AjaxResult showBackUser(HttpServletRequest request) {

        AjaxResult result = AjaxResult.isOk("查询成功", null);
        User user = userService.queryUser(request);
        result.setObj(user);
        return result;
    }

    /**
     * 用户数据管理,禁用
     * success : function(data){
     * $("#myModal").modal("show");
     * $("#user_id").val(data.obj.id);
     * $("#username").val(data.obj.nickname);
     * $("#roleName").val(data.obj.role);
     * $("#email").val(data.obj.email);
     * }不需要分页
     *
     * @param request
     * @return
     */
    @RequestMapping("/modifyBackUser.do")
    @ResponseBody
    public AjaxResult modifyBackUser(HttpServletRequest request) {

        AjaxResult result = AjaxResult.isOk(null, null);
        String results = userService.changeUsers(request);
        result.setMsg(results);
        return result;
    }

    /**
     * 用户数据管理,登录
     *
     * @param request
     * @return
     */
    @RequestMapping("/loginBack.do")
    @ResponseBody
    public AjaxResult loginBack(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
//        先判断验证码
        String code = request.getParameter("code");
        String code1 = String.valueOf(request.getSession().getAttribute(Constant.SESSION_CODE));
        System.out.println(code1);
        if (!code.equals(code1)) {
            AjaxResult result2 = AjaxResult.isFail("验证码错误", null);
            return result2;
        }
        AjaxResult result = AjaxResult.isOk("success", null);
        AjaxResult result1 = AjaxResult.isFail("error", null);
        int results = userService.loginBack(request);
        return ((results > 0) ? result : result1);
    }

    /**
     * 用户数据管理,后端退出登录
     *
     * @param
     * @return
     */
    @RequestMapping("/loginBackOut.do")
    public String loginOut(HttpServletRequest req) {
//        退出时，返回到登录界面
        req.getSession().removeAttribute("sessionUser");
        return "/background/back_login";
    }

    //    前台退出登录
    @RequestMapping("/loginOut.do")
    public String loginOut(HttpSession session) {
        session.removeAttribute(Constant.SESSION_USER);
        return "redirect:/index.do";
    }


    //===========================================
// 注册
//    检查注册登录名
    @RequestMapping("/check.do")
    @ResponseBody
    public AjaxResult check(String login_name) {
        System.out.println("loginName=" + login_name);
        // 可用是true，不可用是false
        String msg = "";
        try {
            if (userService.checkLoginName(login_name)) {
                return AjaxResult.isOk();
            }
        } catch (ServiceException e) {
            System.out.println("name_Exception_msg=" + msg);
            msg = e.getMessage();
        }
        System.out.println("name_msg=" + msg);
        return AjaxResult.isFail(msg);
    }

    //    检查注册邮箱
    @RequestMapping("/checkEmail.do")
    @ResponseBody
    public AjaxResult checkEmail(String email) {
        System.out.println("email=" + email);
        String msg = "";
        try {
            if (userService.checkEmail(email)) {
                return AjaxResult.isOk();
            }
        } catch (ServiceException e) {
            msg = e.getMessage();
        }
        return AjaxResult.isFail(msg);
    }

    //    用户注册
    @RequestMapping("/regist.do")
    @ResponseBody
    public AjaxResult regist(String login_name, String password, String rePassword, String nickname, String email) {
        System.out.println("login_name=" + login_name +
                "&password=" + password + "&rePassword=" + rePassword +
                "&nickname=" + nickname + "&email=" + email);

//        将获取的数据封装成对象
//        id（自增）,login_name,nickname,password,role,email,create_date,statu
        User user = new User();
        user.setLogin_name(login_name);
        user.setNickname(nickname);
        user.setPassword(password);
        user.setRole(Constant.USER_ROLE_NORMAL);
        user.setEmail(email);
        user.setCreate_date(new Date());
        user.setStatus(Constant.STATUS_ENABLE);

//        调用service进行注册，并返回信息
        String msg = "";
        try {
            if (userService.registUser(user)) {
                return AjaxResult.isOk();
            }
        } catch (ServiceException e) {
            msg = e.getMessage();
        }
        return AjaxResult.isFail(msg);
    }


    //  登录
    @RequestMapping("/loginFront.do")
    public String loginFront(String login_name, String password, HttpSession session) {
        System.out.println("login_name=" + login_name + ",password=" + password);

//        排除直接刷新loginFront.do的状况
        if (ParameterUtil.isNull(login_name) && ParameterUtil.isNull(password)) {
            return "front/front_index";
        }

//        将session中的原有信息清空
        session.removeAttribute(Constant.ERROR_MESSAGE);
//        session.removeAttribute(Constant.SESSION_USER);
//        设置Session的生命周期
        session.setMaxInactiveInterval(Constant.SESSION_AGE);

        // 查到是true，查不到是false
        try {
            User result = userService.login(login_name, password);
            session.setAttribute(Constant.SESSION_USER, result);
        } catch (ServiceException e) {
            session.setAttribute(Constant.ERROR_MESSAGE, e.getMessage());
        }
        return "front/front_index";
    }

    // 判断是否需要签到
    @RequestMapping("/findLoginDate.do")
    @ResponseBody
    public User findLoginDate(HttpSession session) {
//        登录后判断
        User user = (User) session.getAttribute(Constant.SESSION_USER);
        System.out.println(user);
        User result = new User();
        try {
            result = userService.findLoginDate(user);
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return result;
    }

    //    签到后更新时间
    @RequestMapping("updateLoginDate.do")
    @ResponseBody
    public AjaxResult updateLoginDate(Integer id) {
        try {
            if (userService.updateLoginDate(id)) {
                return AjaxResult.isOk();
            }
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return AjaxResult.isFail();
    }

    //    修改用户信息
    @RequestMapping("/modifyUser.do")
    @ResponseBody
    public AjaxResult modifyUser(Integer id, String password, String newPassword,
                                 String rePassword, String nickname, String email) {
        System.out.println("id=" + id + ",oldPassword=" + password + ",password=" + newPassword +
                ",rePassword=" + rePassword + ",nickname=" + nickname + ",email=" + email);
        if (ParameterUtil.isNull(password) || ParameterUtil.isNull(newPassword) || ParameterUtil.isNull(rePassword)) {
            return AjaxResult.isFail("请将密码填写全！");
        }
        if (password.equals(newPassword)) {
            return AjaxResult.isFail("新旧密码相同！");
        }
        if (!newPassword.equals(rePassword)) {
            return AjaxResult.isFail("新密码与确认密码不同！");
        }

//        封装参数
        User user = new User();
        user.setId(id);
        user.setPassword(newPassword);
        user.setNickname(nickname);
        user.setEmail(email);

//        返回信息
        String msg = "";
        try {
            if (userService.changeUser(user)) {
                return AjaxResult.isOk("修改信息成功！");
            }
        } catch (ServiceException e) {
            msg = e.getMessage();
        }
        System.out.println("modifyUser_msg=" + msg);
        return AjaxResult.isFail(msg);
    }

}
